package com.yj.generator.core;

import com.yj.generator.entity.GenerateOut;
import com.yj.generator.entity.Table;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

/**
 * @author DengLin
 * @title mapper 生成
 * @date 2024/07/05
 */
public class MapperGeneratorFileImpl implements GenerateFile {
    private static final Logger log = LogManager.getLogger(MapperGeneratorFileImpl.class);

    public void generate(Configuration configuration, GenerateOut generateOut, Map<String, Object> model, File parentFile) {
        model.put("package", generateOut.getOutPackage() + "." + generateOut.getOutMapper());
        model.put("entityPath", generateOut.getOutPackage() + "." + generateOut.getOutEntity());
        Writer writer = null;
        Writer mapperXmlWriter = null;
        try {
            File targetFile = new File(parentFile, generateOut.getOutMapper().replaceAll("\\.", "\\\\"));
            if (!targetFile.exists()) {
                System.out.println(targetFile.mkdir());
            }
            Table table = (Table) model.get("table");
            writer = new FileWriter(new File(targetFile, table.getBeanName() + "Mapper.java"));
            Template template = configuration.getTemplate("mapper.ftl");
            template.process(model, writer);

            String outPath = generateOut.getOutPath();

            File mapperFile = new File(outPath + "src\\main\\resources\\mapper");
            if (!mapperFile.exists()) {
                mapperFile.mkdir();
            }

            mapperXmlWriter = new FileWriter(new File(mapperFile,table.getBeanName()+"Mapper.xml"));
            template = configuration.getTemplate("mapper-xml.ftl");
            template.process(model,mapperXmlWriter);

        } catch (Exception e) {
            log.error("实体Mapper文件生成失败:{}", e.getMessage());
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    log.error("文件关闭失败");
                }
            }

            if (mapperXmlWriter != null) {
                try {
                    mapperXmlWriter.close();
                } catch (IOException e) {
                    log.error("文件关闭失败:{}", e.getMessage());
                }
            }
        }


    }

    @Override
    public void generate(GenerateOut generateOut, Map<String, Object> model) {
        String beanFileName = generateOut.getOutEntity();
        String mapperFileName = generateOut.getOutMapper();
        model.put("beanModule",beanFileName);
        model.put("module",mapperFileName);
    }
}
